package com.cndym.utils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.cndym.adapterForMobile.utils.Base64;

/**
 * 拉卡拉钱包支付 秘钥
 * @author huangsh
 *
 */
public class LklSignUtils {
	
	/**
	 * RSA签名  sha1withrsa算法
	 * @param reqData
	 * @param signAlgorithm
	 * @param priKey
	 * @return
	 */
	public static byte[] sign(String reqData,String signAlgorithm,String priKey) {
		try {
			KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey.getBytes()));
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey prk= keyFactory.generatePrivate(keySpec);
			Signature signetcheck = Signature.getInstance(signAlgorithm);
			signetcheck.initSign(prk);
			signetcheck.update(reqData.getBytes());
			byte[] sign = signetcheck.sign();
			return sign;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return null;
	}
	
	
	//RSA验签  sha1withrsa算法
	public static boolean verify(String reqData,String sign,String signAlgorithm,String pubkey) {
		try {
			
			KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(pubkey.getBytes()));
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PublicKey pubk= keyFactory.generatePublic(keySpec);
			Signature signetcheck = Signature.getInstance(signAlgorithm);
			signetcheck.initVerify(pubk);
			signetcheck.update(Base64.decodeBase64(reqData.getBytes()));
			return  signetcheck.verify(Base64.decodeBase64(sign.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return false;
	}
	
    /** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

}
